﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace EasyTool
{
    public partial class EasyTool : Form
    {
        public EasyTool()
        {
            InitializeComponent();
        }

        private void button15_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            string[] strings = format.Split('\n');
            int len = strings.Length;
            StringBuilder sbu = new StringBuilder();
            for (int i = 0; i < len; i++)
            {
                sbu.Append($"{Underline2Upper(strings[i])}\n");
            }
            sql.Text = sbu.ToString();
        }

        private static string Underline2Upper(string format)
        {
            StringBuilder builder = new StringBuilder();
            char[] charArray = format.ToLower().ToCharArray();
            bool nextIsUpper = false;
            foreach (char c in charArray)
            {
                if (c.Equals('_'))
                {
                    nextIsUpper = true;
                    continue;
                }

                if (nextIsUpper)
                {
                    string info = c.ToString();
                    builder.Append(info.ToUpper());
                    nextIsUpper = false;
                    continue;
                }

                builder.Append(c);
            }

            return builder.ToString();
        }

        private void button20_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            string[] strings = format.Split('\n');
            int len = strings.Length;
            StringBuilder sbu = new StringBuilder();
            for (int i = 0; i < len; i++)
            {
                sbu.Append($"{hump2Underline(strings[i])}\r\n");
            }
            sql.Text = sbu.ToString();

        }
        public string hump2Underline(string str)
        {
            StringBuilder builder = new StringBuilder();
            char[] charArray = str.ToCharArray();
            foreach (char c in charArray)
            {
                if (c > 64 && c < 91)
                {
                    builder.Append("_");
                    builder.Append((char)(c + 32));
                }
                else
                {
                    builder.Append(c);
                }
            }

            return builder.ToString();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;

            bool isInitial = true;
            StringBuilder builder = new StringBuilder();
            //[0]字段名称
            char[] charArray = format.ToCharArray();
            foreach (char c in charArray)
                if (c == '_')
                {
                    builder.Append(' ');
                    isInitial = true;
                }
                else
                {
                    if (isInitial)
                    {
                        builder.Append(c.ToString().ToUpper());
                        isInitial = false;
                    }
                    else
                    {
                        builder.Append(c);
                    }
                }

            sql.Text = builder.ToString().ToLower();
        }

        private void button19_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            sql.Text = format.ToLower();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;

            StringBuilder builder = new StringBuilder();
            //[0]字段名称
            char[] charArray = format.ToCharArray();
            foreach (char c in charArray)
                if (c == ' ')
                    builder.Append('_');
                else
                    builder.Append(c);
            sql.Text = builder.ToString().ToUpper();
        }

        private void button16_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;

            sql.Text = format.ToUpper();
        }

        private void button12_Click(object sender, EventArgs e)
        {
            string content = formatTextBox.Text;
            StringBuilder sbdOutput = new StringBuilder();
            if (content != null)
            {
                StringBuilder sbdInput = new StringBuilder(content);
                for (int intIndex = 0; intIndex < sbdInput.Length; intIndex++)
                {
                    char chrInput = sbdInput[intIndex];
                    if (chrInput == '"')
                        sbdOutput.Append("\\" + chrInput);
                    else if (chrInput != '\n' && chrInput != '\r' && chrInput != '\t') sbdOutput.Append(chrInput);
                }
            }
            sql.Text = sbdOutput.ToString();
        }

        private void button13_Click(object sender, EventArgs e)
        {
            string content = formatTextBox.Text;
            sql.Text = Base64.EncodeBase64(content);
        }

        private void button14_Click(object sender, EventArgs e)
        {
            string content = formatTextBox.Text;
            sql.Text = Base64.DecodeBase64(content);
        }

        private void divide_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            string[] strings = format.Split('\n');
            int len = strings.Length;
            string di = divider.Text.Trim();
            StringBuilder sbu = new StringBuilder();
            for (int i = 0; i < len; i++)
            {
                sbu.Append($"{strings[i].Replace("\r", "")}{di}");
            }
            sql.Text = sbu.ToString();
        }

        private void button18_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            string[] strings = format.Split('\n');
            int len = strings.Length;
            StringBuilder sbu = new StringBuilder();
            int num;
            if (!int.TryParse(numStart.Text, out num))
            {
                num = 1;
            }
            for (int i = 0; i < len; i++)
            {
                sbu.Append($"{num}) {strings[i]}\n");
                num++;
            }

            sql.Text = sbu.ToString();
        }

        private void button17_Click(object sender, EventArgs e)
        {
            StringBuilder result = new StringBuilder(100);
            string prefix = this.prefix.Text;
            string divider = this.divider.Text;
            if (int.TryParse(numStart.Text, out int num1) && int.TryParse(numEnd.Text, out int num2))
            {
                for (int i = num1; i <= num2; i++)
                {
                    result.Append(prefix + i)
                        .Append(divider);
                }

                sql.Text = result.ToString();
            }
            else
            {
                MessageBox.Show(@"起终必须为数字");
            }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            string[] strings = format.Split('\n');
            int len = strings.Length;
            string prefixText = normalPrefix.Text;
            StringBuilder sbu = new StringBuilder();
            for (int i = 0; i < len; i++)
            {
                sbu.Append($"{prefixText}{strings[i]}\n");
            }

            sql.Text = sbu.ToString();
        }

        private void button22_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            string[] strings = format.Split('\n');
            int len = strings.Length;
            string sufixText = normalSuffix.Text;
            StringBuilder sbu = new StringBuilder();
            for (int i = 0; i < len; i++)
            {
                sbu.Append($"{strings[i].Replace("\r", "")}{sufixText}\r\n");
            }

            sql.Text = sbu.ToString();
        }

        private void replace_Click(object sender, EventArgs e)
        {
            string oldStr = oldTextbox.Text;
            string newStr = NewTextbox.Text;
            string text = formatTextBox.Text;
            sql.Text=text.Replace(oldStr, newStr);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            string dvd = divider.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            sql.Text=format.Replace(dvd, "\r\n");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string dir = formatTextBox.Text;


        }

        private void button3_Click(object sender, EventArgs e)
        {
            string startDirectoryPath = from_directory_textBox.Text;
            List<FileInfo> lst = new List<FileInfo>();
            string strPath = startDirectoryPath;
            string searchText = check_textBox.Text;
            List<FileInfo> lstFiles = getFile(strPath, "."+ suffix_textBox.Text, lst);
            foreach (FileInfo shpFile in lstFiles)
            {
                if (check(shpFile.FullName,searchText))
                {
                    formatTextBox.Text += shpFile.FullName + "\r\n";
                }
            }

            MessageBox.Show(@"查找完成");
        }

        /// <summary>
        /// 去除文件bom头后的字符
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static string GetUTF8String(byte[] buffer,out bool result)
        {
            result = false;
            if (buffer == null)
                return null;

            if (buffer.Length <= 3)
            {
                return Encoding.UTF8.GetString(buffer);
            }

            byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };

            if (buffer[0] == bomBuffer[0]
                && buffer[1] == bomBuffer[1]
                && buffer[2] == bomBuffer[2])
            {
                result = true;
                return new UTF8Encoding(false).GetString(buffer, 3, buffer.Length - 3);
            }

            return Encoding.UTF8.GetString(buffer);
        }

        public bool clean(string path)
        {
            byte[] bs = File.ReadAllBytes(path);
            byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };
            if (bs.Length<=3)
            {
                return false;
            }
            if (bs[0] == bomBuffer[0]
                && bs[1] == bomBuffer[1]
                && bs[2] == bomBuffer[2])
            {
                using (var sink = new StreamWriter(path, false, new System.Text.UTF8Encoding(false)))
                {
                    sink.Write(new UTF8Encoding(false).GetString(bs, 3, bs.Length - 3));
                }
            }
            return false;
        }

        public bool check(string path,string searchText)
        {
            StreamReader sr = new StreamReader(path, Encoding.UTF8);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                if(line.IndexOf(searchText, StringComparison.Ordinal)>-1)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获得目录下所有文件或指定文件类型文件(包含所有子文件夹)
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <param name="extName">扩展名可以多个 例如 .mp3.wma.rm</param>
        public List<FileInfo> getFile(string path, string extName, List<FileInfo> lst)
        {
            try
            {
                string[] dir = Directory.GetDirectories(path); //文件夹列表   
                DirectoryInfo fdir = new DirectoryInfo(path);
                FileInfo[] file = fdir.GetFiles();
                if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空                   
                {
                    foreach (FileInfo f in file) //显示当前目录所有文件   
                    {
                        if (extName.ToLower().IndexOf(f.Extension.ToLower(), StringComparison.Ordinal) >= 0)
                        {
                            lst.Add(f);
                        }
                    }
                    foreach (string d in dir)
                    {
                        getFile(d, extName, lst);//递归   
                    }
                }
                return lst;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return lst;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string text = formatTextBox.Text;
            text = text.Replace("\"", "\'");
            string[] strings = text.Split('\n');
            int len = strings.Length;
            StringBuilder sbu = new StringBuilder();
            sbu.AppendLine("StringBuilder sbu = new StringBuilder();");
            for (int i = 0; i < len; i++)
            {
                sbu.AppendLine($"sbu.Append(\"{strings[i].Replace("\r","").Replace("\n","")}\");");
            }
            sql.Text = sbu.ToString();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            string[] strings = format.Split('\n');
            int len = strings.Length;
            StringBuilder sbu = new StringBuilder();
            for (int i = 0; i < len; i++)
            {
                if (string.IsNullOrWhiteSpace(strings[i]))
                {
                    continue;
                }
                sbu.Append($"{strings[i]}\n");
            }

            sql.Text = sbu.ToString();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (int.TryParse(numStart.Text, out int numS) && int.TryParse(this.divider.Text, out int numDivid))
            {
                numS -= 1;
                string format = formatTextBox.Text;
                if (string.IsNullOrWhiteSpace(format)) return;
                string[] strings = format.Split('\n');
                int len = strings.Length;
                StringBuilder sbu = new StringBuilder();
                numDivid++;
                for (int i = numS; i < len; i+= numDivid)
                {
                    sbu.Append($"{strings[i]}\n");
                }
                sql.Text = sbu.ToString();
            }
            else
            {
                MessageBox.Show(@"起终必须为数字");
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            string strPatten = regex_textBox.Text;
            Regex rex = new Regex(strPatten, RegexOptions.IgnoreCase);
            MatchCollection matches = rex.Matches(format);
            StringBuilder sbu = new StringBuilder();
            // 提取匹配项
            foreach (Match match in matches)
            {
                //string matchValue = ;
                sbu.AppendLine(match.Value);
                /*GroupCollection groups = match.Groups;
                //提取匹配项内的分组信息
                for (int i = 0; i < groups.Count; i++)
                {
                    string value = groups[i].Value;
                }*/
            }
            sql.Text = sbu.ToString();

        }

        private void button11_Click(object sender, EventArgs e)
        {
            string content = formatTextBox.Text;
            sql.Text = UrlTool.UrlDecode(content);
        }

        private void button10_Click(object sender, EventArgs e)
        {
            string content = formatTextBox.Text;
            sql.Text = UrlTool.UrlEncode(content);
        }

        private void cleanBom_Click(object sender, EventArgs e)
        {
            string startDirectoryPath = from_directory_textBox.Text;
            List<FileInfo> lst = new List<FileInfo>();
            string strPath = startDirectoryPath;
            List<FileInfo> lstFiles = getFile(strPath, "." + suffix_textBox.Text, lst);
            foreach (FileInfo shpFile in lstFiles)
            {
                if (clean(shpFile.FullName))
                {
                    formatTextBox.Text += shpFile.FullName + "\r\n";
                }
            }

            MessageBox.Show(@"查找完成");
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;
            string[] strings = format.Split('\n');
            for (int i = 0, len = strings.Length; i < len; i++)
            {
                strings[i] = strings[i].Replace("\t", "    ");
            }

            int maxLength = getMaxLength(strings);
            string sufixText = normalSuffix.Text;
            StringBuilder sbu = new StringBuilder();
            for (int i = 0, len = strings.Length; i < len; i++)
            {
                sbu.Append($"{strings[i].Replace("\r", "")}{new string(' ', maxLength-strings[i].Length)}{sufixText}\r\n");
            }

            sql.Text = sbu.ToString();
        }

        private int getMaxLength(string[] strings)
        {
            int max = 0;
            foreach (string s in strings)
            {
                max = s.Length > max ? s.Length : max;
            }
            return max;
        }

        private void button12_Click_1(object sender, EventArgs e)
        {
            formatTextBox.Text = sql.Text;
            sql.Text = "";
        }

        private void button23_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(sql.Text);
        }

        private void button24_Click(object sender, EventArgs e)
        {
            IDataObject iData = Clipboard.GetDataObject();
            if (iData != null && iData.GetDataPresent(DataFormats.Text))
            {
                //如果剪贴板中的数据是文本格式 
                this.formatTextBox.Text = (string)iData.GetData(DataFormats.Text);//检索与指定格式相关联的数据 
            }
            else
            {
                MessageBox.Show("目前剪贴板中数据不可转换为文本", "错误");
            }
        }

        private void vo_extract_Click(object sender, EventArgs e)
        {
            var path = filePath.Text;
            if (string.IsNullOrWhiteSpace(path))
            {
                MessageBox.Show("请填写文件路径！", "错误");
                return;
            }
            var format1 = format.Text;
            if (string.IsNullOrWhiteSpace(format1))
            {
                MessageBox.Show("请填写输出格式！", "错误");
                return;
            }
            string content = File.ReadAllText(path, Encoding.UTF8);
            formatTextBox.Text = content;
            string strPatten = @"private[0-9a-zA-Z <>]*;";
            Regex rex = new Regex(strPatten, RegexOptions.IgnoreCase);
            MatchCollection matches = rex.Matches(content);
            StringBuilder sbu = new StringBuilder();
            // 提取匹配项
            foreach (Match match in matches)
            {
                string[] strings = match.Value.Replace(";", "").Split(' ');
                sbu.AppendLine(string.Format(format1,strings[1], System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(strings[2])));
            }
            sql.Text = sbu.ToString();
        }

        private void button24_Click_1(object sender, EventArgs e)
        {
            string xml = formatTextBox.Text;
            xml=xml.Replace("\\r\\n", "");
            xml = xml.Replace("\"", "");
            xml = xml.Replace("+","" );
            sql.Text = FormatXml(xml);
        }

        private string FormatXml(string sUnformattedXml)
        {
            XmlDocument xd = new XmlDocument(); 
            xd.LoadXml(sUnformattedXml); 
            StringBuilder sb = new StringBuilder(); 
            StringWriter sw = new StringWriter(sb); 
            XmlTextWriter xtw = null;
            try
            {
                using (xtw = new XmlTextWriter(sw))
                {
                    xtw.Formatting = Formatting.Indented;
                    xtw.Indentation = 1;
                    xtw.IndentChar = ' ';
                    xd.WriteTo(xtw);
                }
            }
            finally
            {
                xtw?.Close();
            } 
            return sb.ToString();
        }
        string[] toLower(string[] strs)
        {
            for (int i = 0; i < strs.Length; i++)
            {
                strs[i] = strs[i].Trim().ToLower();
            }
            return strs;
        }
        private void button25_Click(object sender, EventArgs e)
        {
            string r1t = r1.Text;
            if (string.IsNullOrWhiteSpace(r1t)) return;
            string[] r1s = toLower(r1t.Split('\n'));

            string r2t = r2.Text;
            if (string.IsNullOrWhiteSpace(r1t)) return;
            string[] r2s = toLower(r2t.Split('\n'));
            HashSet<string> r2set = new HashSet<string>();
            foreach (string item in r2s)
            {
                r2set.Add(item);
            }

            HashSet<string> r1set = new HashSet<string>();
            foreach (string item in r1s)
            {
                r1set.Add(item);
            }

            IEnumerable<string> enumerable = r1set.Except(r2set);
            IEnumerable<string> enumerable2 = r2set.Except(r1set);
            StringBuilder sbu = new StringBuilder();
            foreach (var item in enumerable)
            {
                sbu.AppendLine("left:"+item);
            }
            foreach (var item in enumerable2)
            {
                sbu.AppendLine("right:"+item);
            }
            result.Text = sbu.ToString();
        }

        private void button26_Click(object sender, EventArgs e)
        {
            string r1t = r1.Text;
            if (string.IsNullOrWhiteSpace(r1t)) return;
            string[] r1s = r1t.Split('\n');

            string r2t = r2.Text;
            if (string.IsNullOrWhiteSpace(r1t)) return;
            string[] r2s = r2t.Split('\n');
            HashSet<string> r2set = new HashSet<string>();
            foreach (string item in r2s)
            {
                r2set.Add(item);
            }

            HashSet<string> r1set = new HashSet<string>();
            foreach (string item in r1s)
            {
                r1set.Add(item);
            }

            IEnumerable<string> enumerable = r1set.Except(r2set);
            IEnumerable<string> enumerable2 = r2set.Except(r1set);
            StringBuilder sbu = new StringBuilder();
            foreach (var item in enumerable)
            {
                sbu.AppendLine("left:" + item);
            }
            foreach (var item in enumerable2)
            {
                sbu.AppendLine("right:" + item);
            }
            result.Text = sbu.ToString();
        }

        private void button27_Click(object sender, EventArgs e)
        {
            string format = formatTextBox.Text;
            if (string.IsNullOrWhiteSpace(format)) return;

            StringBuilder builder = new StringBuilder();
            //[0]字段名称
            char[] charArray = format.ToCharArray();
            foreach (char c in charArray)
                if (c == ' ')
                    builder.Append('_');
                else
                    builder.Append(c);
            sql.Text = builder.ToString().ToLower();
        }
    }
}
